package cloud.xlh.infrastructure.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/1/16 16:01
 * @ Description: 远程调用工具类
 */

@Slf4j
public class RestTemplateUtil {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * POST请求
     */

    public <T> T postForObject(String url, Object reqBody, Map<String, String> formParams, Map<String, String> headerMap, Class<T> cls, String contentType) {
        if (MediaType.APPLICATION_JSON_VALUE.equals(contentType)) {
            return JSONPost(url, reqBody, headerMap, cls);
        } else if (MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)) {
            return formPost(url, formParams, headerMap, cls);
        } else {

        }
        return null;
    }

    /**
     * JSON格式
     */
    public <T> T JSONPost(String url, Object reqBody, Map<String, String> headerMap, Class<T> cls) {
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        if (!CollectionUtils.isEmpty(headerMap)) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                headers.set(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<Object> request = new HttpEntity<>(reqBody, headers);
        return executePost(url, request, cls);
    }

    /**
     * FORM格式
     */
    public <T> T formPost(String url, Map<String, String> params, Map<String, String> headerMap, Class<T> cls) {
        HttpHeaders headers = new HttpHeaders();
        if (!CollectionUtils.isEmpty(headerMap)) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                headers.set(entry.getKey(), entry.getValue());
            }
        }
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<Object> request = new HttpEntity<>(params, headers);
        return executePost(url, request, cls);
    }

    private <T> T executePost(String url, HttpEntity<Object> request, Class<T> cls) {
        ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.POST, request, cls);
        T body = exchange.getBody();
        log.info("post result:{}", body);
        return body;
    }

}
